package com.geline.mybatisplus.context;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mx
 * @date 2025/9/16
 */
@Slf4j
public class ExtractAfterThreadLocal {
    private ThreadLocal<Map<String, Object>> extractAfterLocal = ThreadUtil.createThreadLocal(false);

    public void set(String targetTable, Serializable idValue, Object entity) {
        Map<String, Object> bean = extractAfterLocal.get();
        if (bean == null) {
            bean = new HashMap<>();
        }
        String key = targetTable + ":" + idValue;
        if(bean.get(key)==null){
            bean.put(key, entity);
            extractAfterLocal.set(bean);
            log.debug(">>> extractAfterLocal set {}={}", key, entity);
        }
    }

    public Map<String, Object> getMap() {
        return extractAfterLocal.get();
    }

    public Object getValue(String targetTable, Serializable idValue) {
        Map<String, Object> map = getMap();
        if(map==null){
            return null;
        }
        String key = targetTable + ":" + idValue;
        return map.get(key);
    }

    public void remove() {
        extractAfterLocal.remove();
    }
}
